<script setup>
import { addSetting } from '@/api/system/setting'
const emit = defineEmits(['on-success'])
const visible = ref(false)
const { proxy } = getCurrentInstance()
const formLabelWidth = '120px'
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref([])
const uploadFile = ref(null)
const loading = ref(false)
const form = reactive({
  loginTitle: '',
  fileList: [],
  isActive: 0
})
const rules = reactive({
  loginTitle: [
    { required: true, message: '请输入登录标题', trigger: 'blur' }
  ],
  fileList: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.fileList.length === 0) {
          callback(new Error('请上传图片'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})
const open = () => {
  visible.value = true
}
const handlePictureCardPreview = (uploadFile) => {
  // dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
const handleChange = (file) => {
  console.log(file.size)
  console.log(file)
  dialogImageUrl.value = file.url
  uploadFile.value = file
  console.log(1111, fileList.value)
  if (file.size / 1024 / 1024 > 100) {
    proxy.$message.warning('文件大小不得超过100M,请重新选择')
  }
}
const handleExceed = () => {
  proxy.$message.warning('只能上传一张图片')
}
const submit = async () => {
  proxy.$refs.queryRef.validate(async valid => {
    if (valid) {
      console.log(fileList.value)
      const formData = new FormData()
      formData.append('file', uploadFile.value.raw)
      formData.append('loginTitle', form.loginTitle)
      formData.append('isActive', form.isActive)
      try {
        loading.value = true
        const res = await addSetting(formData)
        console.log(`File uploaded successfully: ${uploadFile.value.name}`, res)
        loading.value = false
        proxy.$message.success('新增成功')
        handleCancel()
        emit('on-success')
      } catch (e) {
        console.error(`Failed to upload file: ${uploadFile.value.name}`, e)
        throw e // 抛出错误以便在 Promise.all 捕获
      }
    }
  })
}
const handleCancel = () => {
  proxy.resetForm('queryRef')
  uploadFile.value = null
  dialogImageUrl.value = ''
  visible.value = false
}
defineExpose({
  open
})
</script>

<template>
  <div>
    <el-dialog
      v-model="visible"
      title="系统配置"
      width="500"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="queryRef"
      >
        <el-form-item
          label="登录标题"
          :label-width="formLabelWidth"
          prop="loginTitle"
        >
          <el-input
            v-model="form.loginTitle"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="登录背景"
          :label-width="formLabelWidth"
          prop="fileList"
        >
          <el-upload
            class="avatar-uploader"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :auto-upload="false"
            accept=".jpg, .png"
            :on-exceed="handleExceed"
            :limit="1"
            v-model:file-list="form.fileList"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">
            取消
          </el-button>
          <el-button
            :loading="loading"
            type="primary"
            @click="submit"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogVisible"
    >
      <img
        style="width: 100%"
        :src="dialogImageUrl"
        alt="Preview Image"
      >
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
